package com.lunatic.rocketmq.service;

import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

@Log4j2
@Service
@RocketMQTransactionListener // 事务消息监听
public class TxConsumerListener implements RocketMQLocalTransactionListener {

    // 执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("exec {}", message);
        String payload = new String((byte[]) message.getPayload());
        if (payload.contains("丢弃")) return RocketMQLocalTransactionState.ROLLBACK;
        if (payload.contains("回查")) return RocketMQLocalTransactionState.UNKNOWN;

        // 模拟本地事务（如数据库操作）
        return RocketMQLocalTransactionState.COMMIT;
    }

    // broker 事务回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("check {}", message);
        // 事务回查逻辑
        return RocketMQLocalTransactionState.COMMIT;
    }
}
